# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.
# frozen_string_literal: true

CCI_SRC ||= ENV['CCI_SRC'] || '/c/compass-ci'

require 'set'
require 'csv'
require_relative "../../lib/es_query.rb"
require_relative "../../lib/es_client.rb"
require_relative '../../lib/json_logger.rb'

DIFF_IFNORE = Set.new([
  "link"
])


def diff_rpms(data)
  begin
    request_body = JSON.parse(data)
    body = diffoscope(request_body)
  rescue StandardError => e
    log_error({
      'message' => e.message,
      'error_message' => "diff rpms error, input #{data}"
    })
    return [500, headers.merge('Access-Control-Allow-Origin' => '*'), "#{data}\n #{e.message}"]
  end
  [200, headers.merge('Access-Control-Allow-Origin' => '*'), body.to_json]
end

def diffoscope(request)
  query_condition = {"id" => request.values}
  es = ESQuery.new(index: 'jobs')
  query_results = es.multi_field_query(query_condition, unmatch_items: {}, size: 10, desc_keyword: "start_time", regexp: nil, single_index: false)
  job_list = query_results['hits']['hits']
  return "need 2 time build at leatest" if job_list.size < 2

  previous_result_root = ''
  current_result_root = ''
  second_job = {}
  job_list.each do |job|
    if job["_id"] == request['second_id'] 
      current_result_root = job["_source"]["result_root"] if job['_id'] == request['second_id']
      second_job = job["_source"]
    else
      previous_result_root = job["_source"]["result_root"] if job['_id'] == request['first_id']
    end
  end

  current_rpm_files = get_rpm(current_result_root)
  previous_rpm_files = get_rpm(previous_result_root)
  return "rpmbuild job has not rpm packages" if current_rpm_files.empty? || previous_rpm_files.empty?

  current_rpm_files.each do |rpm|
    if previous_rpm_files.include?(rpm)
      #cmd = "diffoscope --html #{current_result_root}/#{rpm}.diff-previous.html #{current_result_root}/#{rpm} #{previous_result_root}/#{rpm}"
      #system(cmd)
  		# system("chmod 644  #{current_result_root}/*.html")
      unpacker_rpm(rpm, current_result_root, previous_result_root, second_job)
    end
  end

	es = ESClient.new(index: 'jobs')
  es.put_source_by_id(second_job['id'], second_job)
  

  second_job["reproducible_status"] || {}
end

def get_rpm(path)
  files = Set.new()
  return files unless File.exists?(path)

  Dir.open(path).each do |f|
    next unless f.end_with?(".rpm")
    files << f
  end

  files
end

# summary.csv
# file_path, is_diff, is_unpack, file_type
# /Judy-1.0.5-19.aarch64.rpm,Y,Y,default
# /Judy-1.0.5-19.aarch64.rpm_/Judy-1.0.5-19.aarch64.cpio.xz,Y,Y,default
# /Judy-1.0.5-19.aarch64.rpm_/Judy-1.0.5-19.aarch64.cpio.xz_/Judy-1.0.5-19.aarch64.cpio,Y,Y,cpio
# /Judy-1.0.5-19.aarch64.rpm_/Judy-1.0.5-19.aarch64.cpio.xz_/Judy-1.0.5-19.aarch64.cpio_/usr/share/licenses/Judy/COPYING,N,N,-
# /Judy-1.0.5-19.aarch64.rpm_/Judy-1.0.5-19.aarch64.cpio.xz_/Judy-1.0.5-19.aarch64.cpio_/usr/lib64/libJudy.so.1,N,N,link
# /Judy-1.0.5-19.aarch64.rpm_/Judy-1.0.5-19.aarch64.cpio.xz_/Judy-1.0.5-19.aarch64.cpio_/usr/lib64/libJudy.so.1.0.3,Y,N,NA
def unpacker_rpm(rpm, current_result_root, previous_result_root, job)
	job['reproducible_status'] ||= {}
  cmd = "cd #{current_result_root} && #{CCI_SRC}/src/reproducible-test/Unpacker -sO -x -f #{current_result_root}/#{rpm} #{previous_result_root}/#{rpm}"
  status = system(cmd)
  if status
		test_status = 'reproducible'
		CSV.foreach "#{current_result_root}/summary.csv" do |row|
		  next unless row[2] == 'N' # is_unpack
			next if DIFF_IFNORE.include?(row[3])

		  if row[1] == 'Y' # is_diff
				test_status = 'unreproducible'
				call_diffoscope(rpm, row[0], current_result_root, previous_result_root)
			end
		end

    # job['reproducible_status']['$rpm']: "reproducible"
    # or
    # job['reproducible_status']['$rpm']: "unreproducible"
	  job['reproducible_status'][rpm] = test_status
    if test_status == 'unreproducible'
      diff_dir = "#{current_result_root}/diffoscope"
      system ("mkdir #{diff_dir}") unless File.exist?(diff_dir)
      system("mv #{current_result_root}/*.diff.html #{diff_dir}; chmod -R 755 #{diff_dir}")
    end

  else
		job['reproducible_status'][rpm] = 'Unpack failed'
  end

  # clear result_root
  system("rm #{current_result_root}/summary.csv ; rm -r #{current_result_root}/#{rpm}_ #{previous_result_root}/#{rpm}_")
end

def call_diffoscope(rpm, file, current_result_root, previous_result_root)
  relative_path = file.gsub(current_result_root, '')
  file_name = relative_path.split('/')[-1]
  cmd = "diffoscope --html #{current_result_root}/#{rpm}-#{file_name}.diff.html #{current_result_root}/#{relative_path} #{previous_result_root}/#{relative_path}"
  system(cmd)
end
